import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Space, Popconfirm, Tree, Select, InputNumber } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, FolderOutlined, FolderOpenOutlined } from '@ant-design/icons';
import './ArticleCategory.css';

const { DirectoryTree } = Tree;

const ArticleCategory = () => {
  const [categories, setCategories] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState(null);
  const [form] = Form.useForm();
  const [treeData, setTreeData] = useState([]);

  // 模拟数据加载
  useEffect(() => {
    // 这里应该是从API获取数据
    const mockData = [
      {
        id: 1,
        name: '技术文章',
        description: '技术相关文章',
        parentId: null,
        sort: 1,
        articleCount: 15
      },
      {
        id: 2,
        name: '生活随笔',
        description: '生活相关文章',
        parentId: null,
        sort: 2,
        articleCount: 8
      },
      {
        id: 3,
        name: '前端开发',
        description: '前端技术文章',
        parentId: 1,
        sort: 1,
        articleCount: 10
      },
      {
        id: 4,
        name: '后端开发',
        description: '后端技术文章',
        parentId: 1,
        sort: 2,
        articleCount: 5
      }
    ];
    setCategories(mockData);
    convertToTreeData(mockData);
  }, []);

  const convertToTreeData = (data) => {
    const treeData = data
      .filter(item => item.parentId === null)
      .map(item => ({
        title: `${item.name} (${item.articleCount})`,
        key: item.id,
        icon: <FolderOutlined />,
        children: data
          .filter(child => child.parentId === item.id)
          .map(child => ({
            title: `${child.name} (${child.articleCount})`,
            key: child.id,
            icon: <FolderOpenOutlined />
          }))
      }));
    setTreeData(treeData);
  };

  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '父级分类',
      dataIndex: 'parentId',
      key: 'parentId',
      render: (parentId) => {
        if (parentId === null) return '无';
        const parent = categories.find(cat => cat.id === parentId);
        return parent ? parent.name : '未知';
      },
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '文章数量',
      dataIndex: 'articleCount',
      key: 'articleCount',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            description="删除分类后，相关文章将变为未分类状态"
            onConfirm={() => handleDelete(record.id)}
            okText="是"
            cancelText="否"
          >
            <Button 
              type="danger" 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    setEditingCategory(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingCategory(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = (id) => {
    // 这里应该是调用API删除
    setCategories(categories.filter(cat => cat.id !== id));
    convertToTreeData(categories.filter(cat => cat.id !== id));
    message.success('删除成功');
  };

  const handleOk = () => {
    form.validateFields().then(values => {
      if (editingCategory) {
        // 编辑现有分类
        const updatedCategories = categories.map(cat => 
          cat.id === editingCategory.id ? { ...values, id: editingCategory.id } : cat
        );
        setCategories(updatedCategories);
        convertToTreeData(updatedCategories);
        message.success('更新成功');
      } else {
        // 添加新分类
        const newCategory = {
          ...values,
          id: Date.now(), // 临时ID
          articleCount: 0
        };
        setCategories([...categories, newCategory]);
        convertToTreeData([...categories, newCategory]);
        message.success('添加成功');
      }
      setIsModalVisible(false);
      form.resetFields();
    });
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const getParentOptions = () => {
    return categories
      .filter(cat => cat.parentId === null)
      .map(cat => (
        <Select.Option key={cat.id} value={cat.id}>{cat.name}</Select.Option>
      ));
  };

  return (
    <div className="article-category">
      <div className="category-header">
        <div className="category-tree">
          <h3>分类结构</h3>
          <DirectoryTree
            treeData={treeData}
            defaultExpandAll
          />
        </div>
        <div className="category-actions">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加分类
          </Button>
        </div>
      </div>

      <Table 
        columns={columns} 
        dataSource={categories} 
        rowKey="id"
        pagination={false}
        className="category-table"
      />

      <Modal
        title={editingCategory ? '编辑分类' : '添加分类'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="分类描述"
          >
            <Input.TextArea placeholder="请输入分类描述" />
          </Form.Item>
          <Form.Item
            name="parentId"
            label="父级分类"
          >
            <Select placeholder="请选择父级分类" allowClear>
              {getParentOptions()}
            </Select>
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序' }]}
          >
            <InputNumber min={0} max={999} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ArticleCategory;